#include"SeqList.h"

static void checkcapacity(SeqList* pSL)
{
	assert(pSL);
	if (pSL->capacity == pSL->size)
	{
		int newcapacity = pSL->capacity == 0 ? 4 : 2 * pSL->capacity;
		SLDataType* temp = realloc(pSL->a, sizeof(SLDataType) * newcapacity);
		if (NULL == temp)
		{
			perror("realloc failed");
			exit(-1);
		}
		pSL->a = temp;
		pSL->capacity = newcapacity;
	}
}

void SLInit(SeqList* pSL)
{
	pSL->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	if (NULL == pSL->a)
	{
		perror("malloc failed");
		exit(-1);
	}
	pSL->capacity = pSL->size = 0;
}

void SLDestroy(SeqList* pSL)
{
	free(pSL->a);
	pSL->a = NULL;
	pSL->capacity = pSL->size = 0;
}


void SLInsert(SeqList* pSL, int pos, SLDataType x)
{
	assert(pos >= 0 && pos <= pSL->size);
	checkcapacity(pSL);
	for (int i = pSL->size - 1; i >= pos; --i)
		pSL->a[i + 1] = pSL->a[i];
	pSL->a[pos] = x;
	++pSL->size;
}

SLDataType SLErase(SeqList* pSL, int pos)
{
	assert(pos >= 0 && pos < pSL->size);
	assert(pSL->size);
	SLDataType ret = pSL->a[pos];
	for (int i = pos; i < pSL->size - 1; ++i)
		pSL->a[i] = pSL->a[i + 1];
	--pSL->size;
	return ret;
}

void SLPushBack(SeqList* pSL, SLDataType x)
{
	SLInsert(pSL, pSL->size, x);
}

SLDataType SLPopBack(SeqList* pSL)
{
	return SLErase(pSL, pSL->size - 1);
}

void SLPushFront(SeqList* pSL, SLDataType x)
{
	SLInsert(pSL, 0, x);
}

SLDataType SLPopFront(SeqList* pSL)
{
	return SLErase(pSL, 0);
}